package com.environment_pro.monitor.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import com.environment_pro.monitor.model.TbLogLogin;
import com.environment_pro.monitor.model.User;
import com.environment_pro.monitor.service.TbLogLoginService;
import com.environment_pro.monitor.service.UserService;
import com.environment_pro.monitor.util.StaticUtil;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
	
	private static final Logger logger = Logger.getLogger(UserController.class);

	@Autowired
	private UserService userService;
	
	@Autowired
	private TbLogLoginService tbLogLoginService;
	
	/**
	 * 登录
	 * @param request
	 * @return
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request){
		//已经登录
		String loginname  = StaticUtil.null2String(request.getSession().getAttribute("loginname"));
		if (loginname!=null && loginname.length()>1) { 
			logger.info(loginname + "====login====");
			return "redirect:/user/index";
        } else {  
        	//登录验证
        	loginname  = StaticUtil.null2String(request.getParameter("loginname"));
        	if (loginname!=null && loginname.length()>1) { 
        		logger.info(loginname + "==login==");
        		saveLogLogin(request, loginname);
    			return "redirect:/user/index";
        	}else {  
        		//返回登录页面
        		return "/login"; 
        	}
        }
	}

	private void saveLogLogin(HttpServletRequest request, String loginname) {
		//保存登录日志
		TbLogLogin o = new TbLogLogin();
		o.setLoginDate(new Date());
		o.setLoginSessionId(request.getSession().getId());
		o.setLoginIp(request.getRemoteAddr());//获得客户端的IP地址 
		o.setLoginHostName(request.getRemoteHost());//获得客户端电脑的名字
		o.setLoginUserAgent(request.getHeader("User-agent"));//返回客户端浏览器的版本号、类型
		o.setRealName("realName");
		o.setUserId(1);
		o.setUsername("username");
		request.getSession().setAttribute("loginname", loginname);
		tbLogLoginService.save(o);
	}
	
	/**
	 * 首页
	 * @param request
	 * @return
	 */
	@RequestMapping("/index")
	public String index(HttpServletRequest request){
		String loginname  = StaticUtil.null2String(request.getSession().getAttribute("loginname"));
		logger.info(loginname + "==index==");
		return "/index";
	}
	
	/**
	 * 登出
	 * @param request
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request){
		String loginname  = StaticUtil.null2String(request.getSession().getAttribute("loginname"));
		logger.info(loginname + "==logout==");
		request.getSession().invalidate();
		return "/login";
	}
	
	/**
	 * 获取所有用户列表
	 * @param request
	 * @return
	 */
	@RequestMapping("/getAllUser")
	public String getAllUser(HttpServletRequest request){
		
		List<User> findAll = userService.findAll();
		this.saveLogOperate(request,"");
		request.setAttribute("userList", findAll);
		return "/user/allUser";
	}
	
	/**
	 * 获取所有用户列表
	 * @param request
	 * @return
	 */
	@RequestMapping("/getAllUserJson")
	@ResponseBody
	public List<User> getAllUserJson(HttpServletRequest request){
		
		List<User> findAll = userService.findAll();
		
		return findAll;
	}
	
	/**
	 * 跳转到添加用户界面
	 * @param request
	 * @return
	 */
	@RequestMapping("/toAddUser")
	public String toAddUser(HttpServletRequest request){
		
		return "/user/addUser";
	}
	/**
	 * 添加用户并重定向
	 * @param user
	 * @param request
	 * @return
	 */
	@RequestMapping("/addUser")
	public String addUser(User user,HttpServletRequest request){
		userService.save(user);
		this.saveLogOperate(request,"");
		return "redirect:/user/getAllUser";
	}
	
	/**
	 *编辑用户
	 * @param user
	 * @param request
	 * @return
	 */
	@RequestMapping("/updateUser")
	public String updateUser(User user,HttpServletRequest request){
		
		if(userService.update(user)){
			//user = userService.findById(user.getId());
			this.saveLogOperate(request,"");
			request.setAttribute("user", user);
			return "redirect:/user/getAllUser";
		}else{
			return "/error";
		}
	}
	/**
	 * 根据id查询单个用户
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/getUser")
	public String getUser(int id,HttpServletRequest request){
		
		request.setAttribute("user", userService.findById(id));
		this.saveLogOperate(request,"");
		return "/user/editUser";
	}
	
	/**
	 * 根据id查询单个用户
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/getUserJson")
	@ResponseBody
	public User getUserJson(int id,HttpServletRequest request){
		return userService.findById(id);
	}
	
	/**
	 * 删除用户
	 * @param id
	 * @param request
	 * @param response
	 */
	@RequestMapping("/delUser")
	public void delUser(int id,HttpServletRequest request,HttpServletResponse response){
		String result = "{\"result\":\"error\"}";
		
		if(userService.delete(id)){
			result = "{\"result\":\"success\"}";
		}
		this.saveLogOperate(request,"");
		response.setContentType("application/json");
		
		try {
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
